package com.google.code.avajhelpdesk.pages.users;

import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.avajhelpdesk.components.formbuilder.CustomBeanEditor;
import com.google.code.avajhelpdesk.components.formbuilder.FormSubmitListener;
import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.model.GenericLoadableDetachableModel;
import com.google.code.avajhelpdesk.pages.BasePage;
import com.google.code.avajhelpdesk.persistence.IGenericDAO;

public class UserProfileEdit extends BasePage {

	private static final Logger logger = LoggerFactory.getLogger(UserProfileEdit.class);
	
	private GenericLoadableDetachableModel<User> detachedUser;
	
	private ValueMap data = new ValueMap();
	
	@SpringBean
	private IGenericDAO genericDAO;
	
	public UserProfileEdit(User user) {
		this.detachedUser = new GenericLoadableDetachableModel<User>(user);
		
		InjectorHolder.getInjector().inject(this);
		
		CustomBeanEditor editor = new CustomBeanEditor("editor", new Model(data), new FormSubmitListener() {
			public void onSubmit(Form<?> form, IModel<?> model) {
				User userObject = detachedUser.getObject();
				logger.debug("Changing info for user " + userObject.getUsername());
		
				userObject.setFirstName(data.getString("firstName"));
				userObject.setLastName(data.getString("lastName"));
				userObject.setContactInfo(data.getString("contactInfo"));
				
				genericDAO.merge(userObject);
				
				continueToOriginalDestination();
			}
		});
		
		data.put("username", user.getUsername());
		data.put("firstName", user.getFirstName());
		data.put("lastName", user.getLastName());
		data.put("contactInfo", user.getContactInfo());
		
		editor.appendTextField("username").add(new SimpleAttributeModifier("readonly", "readonly"));
		editor.appendTextField("firstName");
		editor.appendTextField("lastName");
		editor.appendTextArea("contactInfo");
		
		add(editor);
	}
	
	@Override
	protected String getPageTitle() {
		return "Edit user profile";
	}
}
